package com.platform.user.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.platform.bean.JsonResult;
import com.platform.bean.PageInfo;
import com.platform.exception.BaseException;
import com.platform.user.dao.*;
import com.platform.user.dto.AuditItemNoticeDto;
import com.platform.user.entity.*;
import com.platform.utils.BaiduSimilarImageServerUtils;
import com.platform.utils.Base64Utils;
import com.platform.utils.PrintMessageUtils;
import com.platform.utils.UploadFileToRemoteUtils;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class ItemAuditService {

    @Resource
    private LostHelpNoticeDao lostHelpNoticeDao;
    @Resource
    private ItemClaimNoticeDao itemClaimNoticeDao;
    @Resource
    private ItemAuditDao itemAuditDao;
    @Resource
    private ChatRoomDao chatRoomDao;
    @Resource
    private ChatUserDao chatUserDao;
    @Resource
    private ItemQRCodeService itemQRCodeService;
    @Resource
    private ItemQrCodeDao itemQrCodeDao;

    public void deleteAudit(Map<String, Object> params) {
        ItemAudit itemAudit = new ItemAudit();
        itemAudit.setItemId(Integer.parseInt(params.get("itemId").toString()));
        itemAudit.setItemSort(Integer.parseInt(params.get("itemSort").toString()));
        itemAuditDao.deleteByItemIdAndItemSort(itemAudit);
    }

    public void withdrawAudit(Map<String, Object> params) {
        ItemAudit itemAudit = new ItemAudit();
        itemAudit.setAuditStatus(2);
        itemAudit.setItemId(Integer.parseInt(params.get("itemId").toString()));
        itemAudit.setItemSort(Integer.parseInt(params.get("itemSort").toString()));
        itemAuditDao.updateByItemIdAndItemSort(itemAudit);
    }

    public ItemClaimNotice retryAuditFoundItem(Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageFileList = (List<Map<String, Object>>) params.get("imageFileList");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageCoverFileList = (List<Map<String, Object>>) params.get("imageCoverFileList");
//        for (Map<String, Object> o: imageFileList) {
//            System.out.println(o.get("url").toString());
//        }
//        System.out.println("---------------------------");
        String imageCoverUrl = null;
        for (Map<String, Object> o: imageCoverFileList) {
            imageCoverUrl = o.get("url").toString();
        }

//        PrintMessageUtils.traverseMap(params);
        int id = Integer.parseInt(params.get("id").toString());
        System.out.println(id);
        ItemClaimNotice newItemClaimNotice = new ItemClaimNotice();
        ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(id);
        System.out.println(itemClaimNotice.toString());

        List<String> newImageUrlList = new ArrayList<>();
        List<String> oldImageUrlList = new ArrayList<>();
        List<String> deletedImageUrlList = new ArrayList<>();
        List<String> uploadedImageUrlList = new ArrayList<>();

        for (Map<String, Object> o : imageFileList) {
            newImageUrlList.add(o.get("url").toString());
        }

        oldImageUrlList.add(itemClaimNotice.getItemImage1());
        oldImageUrlList.add(itemClaimNotice.getItemImage2());
        oldImageUrlList.add(itemClaimNotice.getItemImage3());

        // 主图找到需要删除的老图片，并存储在List中
        for (String oldUrl : oldImageUrlList) {
            if (oldUrl != null && !newImageUrlList.contains(oldUrl)) {
                deletedImageUrlList.add(oldUrl);
            }
        }

        // 封面判断是否需要删除
        if (imageCoverUrl != null && !imageCoverUrl.equals(itemClaimNotice.getImageCover())) {
            // 需要删除，则存储到List中
            deletedImageUrlList.add(itemClaimNotice.getImageCover());
        }

        try {
            // 尝试更新封面图片
            Boolean ifImageUrl = isImageUrl(imageCoverUrl);
            // 图片不为空 且 不为url，则图片为base64编码
            if (ifImageUrl != null && !ifImageUrl) {
                String imgUrl = processBase64ToUrl(imageCoverUrl);
                itemClaimNotice.setImageCover(imgUrl);
                uploadedImageUrlList.add(imgUrl);
            } else {
                itemClaimNotice.setImageCover(imageCoverUrl);
            }

            // 尝试更新主图
            if (!imageFileList.isEmpty() && imageFileList.get(0) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(0).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(0).get("url").toString());
                    itemClaimNotice.setItemImage1(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    itemClaimNotice.setItemImage1(imageFileList.get(0).get("url").toString());
                }
            }

            if (imageFileList.size() > 1 && imageFileList.get(1) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(1).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(1).get("url").toString());
                    itemClaimNotice.setItemImage2(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    itemClaimNotice.setItemImage2(imageFileList.get(1).get("url").toString());
                }
            }

            if (imageFileList.size() > 2 && imageFileList.get(2) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(2).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(2).get("url").toString());
                    itemClaimNotice.setItemImage3(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    itemClaimNotice.setItemImage3(imageFileList.get(2).get("url").toString());
                }
            }

            System.out.println("新的对象 " + itemClaimNotice.toString());
            System.out.println("需要删除的图片");
            PrintMessageUtils.traverseList(deletedImageUrlList);

            itemClaimNotice.setItemName(params.get("itemName").toString());
            itemClaimNotice.setItemDescription(params.get("itemDescription").toString());
            itemClaimNotice.setContactWay(Integer.parseInt(params.get("contactWay").toString()));
            itemClaimNotice.setFoundTime(parseDate(params.get("foundTime").toString()));
            itemClaimNotice.setItemClassId(Integer.parseInt(params.get("itemClassId").toString()));
            itemClaimNotice.setContactNumber(params.get("contactNumber").toString());
            itemClaimNotice.setFoundPositionCoordinate(params.get("foundPositionCoordinate").toString());
            itemClaimNotice.setFoundPositionDescription(params.get("foundPositionDescription").toString());
            itemClaimNoticeDao.update(itemClaimNotice);

            // 把审核表的属性也更新，包括itemName、auditStatus
            ItemAudit itemAudit = new ItemAudit();
            itemAudit.setItemId(itemClaimNotice.getId());
            itemAudit.setItemSort(1);
            itemAudit.setItemName(itemClaimNotice.getItemName());
            itemAudit.setAuditStatus(0);
            itemAuditDao.updateByItemIdAndItemSort(itemAudit);
        } catch (Exception e) {
            // 处理新上传的图片删除 uploadedImageUrlList
            for (String url: uploadedImageUrlList) {
                if (url != null) {
                    deleteImageByUrl(url);
                }
            }
            e.printStackTrace();
            throw new BaseException("物品生成失败");
        }

        // 处理老图片删除 deletedImageUrlList
        for (String url: deletedImageUrlList) {
            if (url != null) {
                deleteImageByUrl(url);
            }
        }
        return itemClaimNotice;
    }

    public LostHelpNotice retryAuditLostItem(Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageFileList = (List<Map<String, Object>>) params.get("imageFileList");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageCoverFileList = (List<Map<String, Object>>) params.get("imageCoverFileList");
//        for (Map<String, Object> o: imageFileList) {
//            System.out.println(o.get("url").toString());
//        }
//        System.out.println("---------------------------");
        String imageCoverUrl = null;
        for (Map<String, Object> o: imageCoverFileList) {
            imageCoverUrl = o.get("url").toString();
        }

//        PrintMessageUtils.traverseMap(params);
        int id = Integer.parseInt(params.get("id").toString());
        System.out.println(id);
        LostHelpNotice newLostHelpNotice = new LostHelpNotice();
        LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(id);
        System.out.println(lostHelpNotice.toString());

        List<String> newImageUrlList = new ArrayList<>();
        List<String> oldImageUrlList = new ArrayList<>();
        List<String> deletedImageUrlList = new ArrayList<>();
        List<String> uploadedImageUrlList = new ArrayList<>();

        for (Map<String, Object> o : imageFileList) {
            newImageUrlList.add(o.get("url").toString());
        }

        oldImageUrlList.add(lostHelpNotice.getItemImage1());
        oldImageUrlList.add(lostHelpNotice.getItemImage2());
        oldImageUrlList.add(lostHelpNotice.getItemImage3());

        // 主图找到需要删除的老图片，并存储在List中
        for (String oldUrl : oldImageUrlList) {
            if (oldUrl != null && !newImageUrlList.contains(oldUrl)) {
                deletedImageUrlList.add(oldUrl);
            }
        }

//        String changeBaiduImageBase64 = null;
//        // 封面判断是否需要删除
//        if (imageCoverUrl != null && !imageCoverUrl.equals(lostHelpNotice.getImageCover())) {
//            // 需要删除，则存储到List中
//            deletedImageUrlList.add(lostHelpNotice.getImageCover());
//            // 百度智能云修改图片
//            changeBaiduImageBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
//        }

        try {
            // 尝试更新封面图片
            Boolean ifImageUrl = isImageUrl(imageCoverUrl);
            // 图片不为空 且 不为url，则图片为base64编码
            if (ifImageUrl != null && !ifImageUrl) {
                String imgUrl = processBase64ToUrl(imageCoverUrl);
                lostHelpNotice.setImageCover(imgUrl);
                uploadedImageUrlList.add(imgUrl);
            } else {
                lostHelpNotice.setImageCover(imageCoverUrl);
            }

            // 尝试更新主图
            if (!imageFileList.isEmpty() && imageFileList.get(0) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(0).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(0).get("url").toString());
                    lostHelpNotice.setItemImage1(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    lostHelpNotice.setItemImage1(imageFileList.get(0).get("url").toString());
                }
            }

            if (imageFileList.size() > 1 && imageFileList.get(1) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(1).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(1).get("url").toString());
                    lostHelpNotice.setItemImage2(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    lostHelpNotice.setItemImage2(imageFileList.get(1).get("url").toString());
                }
            }

            if (imageFileList.size() > 2 && imageFileList.get(2) != null) {
                Boolean ifItemImage1Url = isImageUrl(imageFileList.get(2).get("url").toString());
                // 图片为base64
                if (!ifItemImage1Url) {
                    String imgUrl = processBase64ToUrl(imageFileList.get(2).get("url").toString());
                    lostHelpNotice.setItemImage3(imgUrl);
                    uploadedImageUrlList.add(imgUrl);
                } else {
                    // 图片为url
                    lostHelpNotice.setItemImage3(imageFileList.get(2).get("url").toString());
                }
            }

            System.out.println("新的对象 " + newLostHelpNotice.toString());
            System.out.println("需要删除的图片");
            PrintMessageUtils.traverseList(deletedImageUrlList);

            lostHelpNotice.setItemName(params.get("itemName").toString());
            lostHelpNotice.setItemDescription(params.get("itemDescription").toString());
            lostHelpNotice.setContactWay(Integer.parseInt(params.get("contactWay").toString()));
            lostHelpNotice.setLostTime(parseDate(params.get("lostTime").toString()));
            lostHelpNotice.setItemClassId(Integer.parseInt(params.get("itemClassId").toString()));
            lostHelpNotice.setContactNumber(params.get("contactNumber").toString());
            lostHelpNotice.setLostPositionCoordinate(params.get("lostPositionCoordinate").toString());
            lostHelpNotice.setLostPositionDescription(params.get("lostPositionDescription").toString());
//            lostHelpNotice.setUserId(Integer.parseInt(params.get("userId").toString()));
//            lostHelpNotice.setItemStatus(0);
//            lostHelpNotice.setIfComplaint(0);
//            lostHelpNotice.setIfViolation(0);
//            lostHelpNotice.setIfControversy(0);
//            lostHelpNoticeDao.insert(lostHelpNotice);
            lostHelpNoticeDao.update(lostHelpNotice);

            // 把审核表的属性也更新，包括itemName、auditStatus
            ItemAudit itemAudit = new ItemAudit();
            itemAudit.setItemId(lostHelpNotice.getId());
            itemAudit.setItemSort(0);
            itemAudit.setItemName(lostHelpNotice.getItemName());
            itemAudit.setAuditStatus(0);
            itemAuditDao.updateByItemIdAndItemSort(itemAudit);
        } catch (Exception e) {
            // 处理新上传的图片删除 uploadedImageUrlList
            for (String url: uploadedImageUrlList) {
                if (url != null) {
                    deleteImageByUrl(url);
                }
            }
            e.printStackTrace();
            throw new BaseException("物品生成失败");
        }

        // 处理老图片删除 deletedImageUrlList
        for (String url: deletedImageUrlList) {
            if (url != null) {
                deleteImageByUrl(url);
            }
        }
//        // 百度智能云修改图片
//        if (changeBaiduImageBase64 != null) {
//
//        }
        return lostHelpNotice;
    }

    public PageInfo<ItemClaimNotice> queryUnAuditFoundByPage(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        params.put("itemSort", 1);
        params.put("auditStatus", 0);
        List<ItemAudit> itemAuditList = itemAuditDao.queryByPage(page, params);

        List<ItemClaimNotice> itemClaimNoticeList = new ArrayList<>();
        for (ItemAudit x: itemAuditList) {
            ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(x.getItemId());
            itemClaimNoticeList.add(itemClaimNotice);
        }
        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        return new PageInfo<>(pageIndex, pageSize, itemAuditDao.countByParams(params), itemClaimNoticeList);
    }

    public PageInfo<LostHelpNotice> queryUnAuditLostByPage(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        params.put("itemSort", 0);
        params.put("auditStatus", 0);

        List<ItemAudit> itemAuditList = itemAuditDao.queryByPage(page, params);
        List<LostHelpNotice> lostHelpNoticeList = new ArrayList<>();
        for (ItemAudit x: itemAuditList) {
            LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(x.getItemId());
            lostHelpNoticeList.add(lostHelpNotice);
        }
        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        return new PageInfo<>(pageIndex, pageSize, itemAuditDao.countByParams(params), lostHelpNoticeList);
    }

    public PageInfo<AuditItemNoticeDto> queryItemByPage(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        List<ItemAudit> itemAuditList = itemAuditDao.queryByPage(page, params);
        List<AuditItemNoticeDto> auditItemNoticeDtoList = new ArrayList<>();
        for (ItemAudit x: itemAuditList) {
            AuditItemNoticeDto auditItemNoticeDto = new AuditItemNoticeDto();
            if (x.getItemSort() == 0) {
                LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(x.getItemId());
                auditItemNoticeDto.setLostHelpNotice(lostHelpNotice);
            } else {
                ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(x.getItemId());
                auditItemNoticeDto.setItemClaimNotice(itemClaimNotice);
            }
            auditItemNoticeDto.setItemId(x.getItemId());
            auditItemNoticeDto.setUserId(x.getUserId());
            auditItemNoticeDto.setAuditStatus(x.getAuditStatus());
            auditItemNoticeDto.setItemSort(x.getItemSort());
            auditItemNoticeDto.setAuditFailedReason(x.getAuditFailedReason());
            auditItemNoticeDtoList.add(auditItemNoticeDto);
        }
        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        return new PageInfo<>(pageIndex, pageSize, itemAuditDao.countByParams(params), auditItemNoticeDtoList);
    }

    public void auditItem(Map<String, Object> params) throws JSONException, IOException {
        int ifAuditPass = Integer.parseInt(params.get("ifAuditPass").toString());
        int itemId = Integer.parseInt(params.get("id").toString());
        int itemSort = Integer.parseInt(params.get("itemSort").toString());
        if (ifAuditPass == 0) {
            // 审核不通过
            ItemAudit itemAudit = new ItemAudit();
            itemAudit.setAuditStatus(1);
            itemAudit.setItemId(itemId);
            itemAudit.setItemSort(itemSort);
            itemAudit.setAuditFailedReason(params.get("auditFailedReason").toString());
            itemAuditDao.updateByItemIdAndItemSort(itemAudit);
        } else {
            // 审核通过
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("itemSort", itemSort);
            queryMap.put("itemId", itemId);
            ItemAudit itemAudit = itemAuditDao.queryOneByParams(queryMap);
            if (itemAudit != null) {
                // 失物求助
                if (itemAudit.getItemSort() == 0) {
                    LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemAudit.getItemId());
                    // 百度智能识图
                    String urlToBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
                    String watermarkBase64 = Base64Utils.addWatermark(urlToBase64);

                    Map<String, Object> baiduImageReq = new HashMap<>();
                    baiduImageReq.put("image", watermarkBase64);
                    baiduImageReq.put("brief", lostHelpNotice.getId());
                    // 失物未找到
                    baiduImageReq.put("classId1", "1");

                    String watermarkImageCoverUrl;

                    try {
                        // 生成水印封面
                        watermarkImageCoverUrl = processBase64ToUrl(watermarkBase64);
                        // 生成失物二维码
                        String QRCodeUrl = itemQRCodeService.generateQRCode("0+" + itemAudit.getItemId().toString());
                        ItemQrCode itemQrCode = new ItemQrCode();
                        itemQrCode.setItemId(itemAudit.getItemId());
                        itemQrCode.setQrCodeImage(QRCodeUrl);
                        itemQrCode.setItemSort(0);
                        itemQrCodeDao.insert(itemQrCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new BaseException("出错");
                    }

                    if (watermarkImageCoverUrl != null) {
                        deleteImageByUrl(lostHelpNotice.getImageCover());
                        lostHelpNotice.setImageCover(watermarkImageCoverUrl);
                    }

                    int i = BaiduSimilarImageServerUtils.addImage(baiduImageReq);
                    if (i != 200) {
                        System.out.println("错误码" + i);
                        return;
                    }

                    lostHelpNotice.setId(itemAudit.getItemId());
                    lostHelpNotice.setItemStatus(1);
                    lostHelpNoticeDao.update(lostHelpNotice);
                    // 新建聊天室
                    LostHelpNotice newLostHelpNotice = lostHelpNoticeDao.queryById(itemAudit.getItemId());
                    ChatRoom chatRoom = new ChatRoom();
                    StringBuilder sb = new StringBuilder();
                    chatRoom.setRoomName(sb.append(newLostHelpNotice.getItemName()).append("聊天室").toString());
                    chatRoom.setItemId(newLostHelpNotice.getId());
                    chatRoom.setUserId(newLostHelpNotice.getUserId());
                    chatRoom.setItemSort(0);
                    chatRoom.setRoomStatus(0);
                    chatRoom.setUserCount(1);
                    chatRoomDao.insert(chatRoom);
                    // 把房主加入到聊天室
                    ChatUser chatUser = new ChatUser();
                    chatUser.setUserId(newLostHelpNotice.getUserId());
                    chatUser.setRoomId(chatRoom.getId());
                    chatUser.setItemId(newLostHelpNotice.getId());
                    chatUser.setItemSort(0);
                    chatUserDao.insert(chatUser);
                } else if (itemAudit.getItemSort() == 1) { // 招领信息
                    ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemAudit.getItemId());
                    // 百度智能识图
                    String urlToBase64 = Base64Utils.convertImageUrlToBase64(itemClaimNotice.getImageCover());
                    String watermarkBase64 = Base64Utils.addWatermark(urlToBase64);

                    Map<String, Object> baiduImageReq = new HashMap<>();
                    baiduImageReq.put("image", watermarkBase64);
                    baiduImageReq.put("brief", itemClaimNotice.getId());
                    // 招领未归还
                    baiduImageReq.put("classId1", "4");

                    String watermarkImageCoverUrl;
                    try {
                        // 生成水印封面
                        watermarkImageCoverUrl = processBase64ToUrl(watermarkBase64);
                        // 生成失物二维码
                        String QRCodeUrl = itemQRCodeService.generateQRCode("1+" + itemAudit.getItemId().toString());
                        ItemQrCode itemQrCode = new ItemQrCode();
                        itemQrCode.setItemId(itemAudit.getItemId());
                        itemQrCode.setQrCodeImage(QRCodeUrl);
                        itemQrCode.setItemSort(1);
                        itemQrCodeDao.insert(itemQrCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new BaseException("出错");
                    }

                    if (watermarkImageCoverUrl != null) {
                        deleteImageByUrl(itemClaimNotice.getImageCover());
                        itemClaimNotice.setImageCover(watermarkImageCoverUrl);
                    }

                    int i = BaiduSimilarImageServerUtils.addImage(baiduImageReq);
                    if (i != 200) {
                        System.out.println("错误码" + i);
                        return;
                    }
                    itemClaimNotice.setId(itemAudit.getItemId());
                    itemClaimNotice.setItemStatus(1);
                    itemClaimNoticeDao.update(itemClaimNotice);
                    // 新建聊天室
                    ItemClaimNotice newItemClaimNotice = itemClaimNoticeDao.queryById(itemAudit.getItemId());
                    ChatRoom chatRoom = new ChatRoom();
                    StringBuilder sb = new StringBuilder();
                    chatRoom.setRoomName(sb.append(newItemClaimNotice.getItemName()).append("聊天室").toString());
                    chatRoom.setItemId(newItemClaimNotice.getId());
                    chatRoom.setUserId(newItemClaimNotice.getUserId());
                    chatRoom.setItemSort(1);
                    chatRoom.setRoomStatus(0);
                    chatRoom.setUserCount(1);
                    chatRoomDao.insert(chatRoom);
                    // 把房主加入到聊天室
                    ChatUser chatUser = new ChatUser();
                    chatUser.setUserId(newItemClaimNotice.getUserId());
                    chatUser.setRoomId(chatRoom.getId());
                    chatUser.setItemId(newItemClaimNotice.getId());
                    chatUser.setItemSort(1);
                    chatUserDao.insert(chatUser);
                }
                // 删除审核记录
                itemAuditDao.deleteById(itemAudit.getId());
            }
        }
    }

    public PageInfo<AuditItemNoticeDto> queryItemPageByUserId(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        List<ItemAudit> itemAuditList = itemAuditDao.queryByPage(page, params);
        List<AuditItemNoticeDto> auditItemNoticeDtoList = new ArrayList<>();
        for (ItemAudit x: itemAuditList) {
            AuditItemNoticeDto auditItemNoticeDto = new AuditItemNoticeDto();
            if (x.getItemSort() == 0) {
                LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(x.getItemId());
                auditItemNoticeDto.setLostHelpNotice(lostHelpNotice);
            } else {
                ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(x.getItemId());
                auditItemNoticeDto.setItemClaimNotice(itemClaimNotice);
            }
            auditItemNoticeDto.setItemId(x.getItemId());
            auditItemNoticeDto.setUserId(x.getUserId());
            auditItemNoticeDto.setAuditStatus(x.getAuditStatus());
            auditItemNoticeDto.setItemSort(x.getItemSort());
            auditItemNoticeDto.setAuditFailedReason(x.getAuditFailedReason());
            auditItemNoticeDtoList.add(auditItemNoticeDto);
        }
        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        return new PageInfo<>(pageIndex, pageSize, itemAuditDao.countByParams(params), auditItemNoticeDtoList);
    }

    public void addItemAudit(Map<String, Object> params) {
        ItemAudit itemAudit = new ItemAudit();
        itemAudit.setAuditStatus(0);
        itemAudit.setUserId(Integer.parseInt(params.get("userId").toString()));
        itemAudit.setItemId(Integer.parseInt(params.get("itemId").toString()));
        itemAudit.setItemSort(Integer.parseInt(params.get("itemSort").toString()));
        itemAudit.setItemName(params.get("itemName").toString());
        System.out.println(itemAudit);
        if (itemAuditDao.queryByItemId(Integer.parseInt(params.get("itemId").toString()),
                Integer.parseInt(params.get("itemSort").toString())) == null) {
            itemAuditDao.insert(itemAudit);
        }
    }

    /**
     * 日期字符串转换为日期对象
     *
     * @param date 日期字符串
     * @return 日期对象
     * @throws ParseException 异常
     */
    private Date parseDate(String date) throws ParseException {
        // 更新其他属性
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat inputFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat inputFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date foundTimeDate = null;

        try {
            foundTimeDate = inputFormat1.parse(date);
        } catch (ParseException e) {
            // 如果第一种格式解析失败，记录信息并继续
            System.out.println("Failed to parse with format 1: " + e.getMessage());
        }

        // 如果第一种格式解析失败，尝试第二种格式
        if (foundTimeDate == null) {
            try {
                foundTimeDate = inputFormat2.parse(date);
            } catch (ParseException e) {
                // 如果第二种格式解析失败，记录信息
                System.out.println("Failed to parse with format 2: " + e.getMessage());
            }
        }

        return foundTimeDate;
    }

    /**
     * 根据url删除图片
     *
     * @param url 图片url
     */
    private void deleteImageByUrl(String url) {
        if (url != null) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(url,
                    "/opt/docker/apache/www/images/lost_and_found");
        }
    }

    /**
     * 判断String是否为图片url
     *
     * @param input 字符串
     * @return 结果
     */
    private Boolean isImageUrl(String input) {
        if (input == null || input.isEmpty()) {
            return null;
        }

        // 正则表达式匹配以 http 或 https 开头，并且是图片格式（如 .jpg, .png, .gif 等）
        String imageUrlPattern = "^(https?://).*\\.(jpg|jpeg|png|gif|bmp|webp)$";
        Pattern pattern = Pattern.compile(imageUrlPattern, Pattern.CASE_INSENSITIVE);
        return pattern.matcher(input).matches();
    }


    /**
     * 将base64封面图片转换为url
     *
     * @param imageBase64 base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processNoPrefixBase64ToPngUrl(String imageBase64) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageBase64);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".png");
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }

    /**
     * 将base64封面图片转换为url
     *
     * @param imageBase64 base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processBase64ToUrl(String imageBase64) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageBase64);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".").append(imageType);
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }

    /**
     * 删除物品详情的所有图片（包括封面、详情图片）
     *
     * @param itemClaimNotice 丢失求助贴
     */
    private void deleteAllItemClaimNoticeImage(ItemClaimNotice itemClaimNotice) {
        // 删除封面图片
        if (itemClaimNotice.getImageCover() != null && !itemClaimNotice.getImageCover().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(itemClaimNotice.getImageCover(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (itemClaimNotice.getItemImage1() != null && !itemClaimNotice.getItemImage1().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(itemClaimNotice.getItemImage1(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (itemClaimNotice.getItemImage2() != null && !itemClaimNotice.getItemImage2().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(itemClaimNotice.getItemImage2(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (itemClaimNotice.getItemImage3() != null && !itemClaimNotice.getItemImage3().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(itemClaimNotice.getItemImage3(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
    }
}
